package com.example.administrator.webviewtest.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.example.administrator.webviewtest.domain.WebViewPayResult;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 支付公共类
 */
public class PayUtils {

    public static Handler meHandler;
    private static String orderNo;
    private static WebViewPayResult payResult2;

    public static WebViewPayResult pay(final Activity activity, AppPayOrder order, final CallBackFunction function, final BridgeWebView myWebView) {
        payResult2 = new WebViewPayResult();
        if (TextUtils.isEmpty(PayResult.PARTNER) || TextUtils.isEmpty(PayResult.RSA_PRIVATE)
                || TextUtils.isEmpty(PayResult.SELLER)) {
            new AlertDialog.Builder(activity)
                    .setTitle("警告")
                    .setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialoginterface, int i) {
                                    //
                                    activity.finish();
                                }
                            }).show();
            return payResult2;
        }
        // 订单
        final String orderInfo = PayResult.getOrderInfo(order);

        // 对订单做RSA 签名
        String sign = PayResult.sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + PayResult.getSignType();
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);
                Message msg = new Message();
                msg.what = PayResult.SDK_PAY_FLAG;
                msg.obj = result;
                meHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();


        meHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case PayResult.SDK_PAY_FLAG: {
                        PayResult payResult = new PayResult((String) msg.obj);

                        // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                        String resultInfo = payResult.getResult();
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            Toast.makeText(activity, "支付成功",
                                    Toast.LENGTH_SHORT).show();
//                        String a=resultInfo.substring(resultInfo.indexOf("&subject\""),resultInfo.indexOf("&body\""));
//                        String[] ary=a.split("=");

                            String a = resultInfo.substring(resultInfo.indexOf("&body"), resultInfo.indexOf("\"&total_fee"));
                            String[] ary = a.split("=\"");
                            orderNo = resultInfo.substring(resultInfo.indexOf("&out_trade_no=\"") + 15, resultInfo.indexOf("\"&subject"));
                            Log.e("支付成功后返回：", "orderNo=     " + orderNo);
                            payResult2.setIsPay(true);
                            payResult2.setOrderNo(orderNo);
                            function.onCallBack(orderNo);

                            //js返回显示支付完成后的页面
                            myWebView.callHandler("payedResult", orderNo, new CallBackFunction() {

                                @Override
                                public void onCallBack(String data) {
                                    // TODO Auto-generated method stub
                                    System.out.println(orderNo);
                                }

                            });
                           /* Intent intent = new Intent(activity, MainActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("itemId", ary[1]);
                            bundle.putString(Constants.FROM, Constants.COME_PAY_SUCCESS);
                            intent.putExtras(bundle);
                            activity.startActivity(intent);*/

                        } else {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000")) {
                                Toast.makeText(activity, "支付结果确认中",
                                        Toast.LENGTH_SHORT).show();

                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                Toast.makeText(activity, "支付失败",
                                        Toast.LENGTH_SHORT).show();
                                payResult2.setIsPay(false);
                                payResult2.setOrderNo(orderNo);
                           /* Intent intent = new Intent(activity, HomeActivity.class);
                            Bundle bundle = new Bundle();

                            bundle.putString(Constants.FROM, Constants.COME_FAIL_SUCCESS);
                            intent.putExtras(bundle);
                            activity.startActivity(intent);*/

                            }
                        }
                        break;
                    }
                    case PayResult.SDK_CHECK_FLAG: {
                        Toast.makeText(activity, "检查结果为：" + msg.obj,
                                Toast.LENGTH_SHORT).show();
                        break;
                    }
                    default:
                        break;
                }
            }

            ;
        };
        return payResult2;
    }
}
